<template>
  <el-dialog :title="dialogTitle" :visible.sync="visible" width="600px" :before-close="handleClose">
     <div class="warning-text">
   <div>* 只能选择当前在线的qq。</div>
   </div>
    <el-form ref="createForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="QQ号" prop="accountId">
        <el-select v-model="form.accountId" filterable clearable placeholder="请选择QQ号" style="width: 100%" @change="calculateCost">
          <el-option v-for="item in hangUpQQList" :key="item.id" :label="item.account" :value="item.id" />
        </el-select>
      </el-form-item>

        <el-form-item label="游戏名称" prop="gameId">
                <el-select v-model="form.gameId" placeholder="请选择游戏" style="width: 100%" clearable @change="gameChange">
                    <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
            </el-form-item>


      <el-form-item label="秘钥" prop="code">
        <el-input v-model="form.code" placeholder="请输入秘钥" clearable  />
      </el-form-item>
      
      <el-form-item label="用户名" prop="useUserName">
        <el-input v-model="form.useUserName" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker v-model="form.expireTime" type="datetime" placeholder="请选择到期时间" style="width: 100%"
          value-format="yyyy-MM-dd HH:mm:ss" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import cardSecretApi from '@/api/tenantApis/cardSecret'
export default {
  name: 'CardSecretModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    hangUpQQList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      id: "",
      form: {
        account: '',
        accountId: null,
        useUserName: '',
        expireTime: '',
        remark: '' , 
        gameId:''
      },
      rules: {
        accountId: [{ required: true, message: '请选择已挂机QQ号', trigger: 'change' }],
        gameId: [{ required: true, message: '请选择游戏', trigger: 'change' }],

        code: [{ required: true, message: '请输入秘钥', trigger: 'blur' }],
        // phone: [
        //   { required: true, message: '请输入手机号', trigger: 'blur' },
        //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        // ],
        expireTime: [{ required: true, message: '请选择到期时间', trigger: 'change' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.id ? '修改秘钥' :'创建秘钥'
    },
     allGameList() {
        return this.$store.getters.allGameList;
      },
  },
  methods: {
    calculateCost(val) {
      this.hangUpQQList.forEach(item => {
        if (item.id === val) {
          this.form.account = item.account
        }
      })
    },
    open(row) {
      this.id = row.id
      this.form = {
        account: row.account,
        accountId: row.accountId,
        useUserName: row.useUserName,
        code: row.code,
        expireTime: row.expireTime,
        remark: row.remark,
        gameId:row.gameId,
        gameName:row.gameName
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.resetForm()
    },
    gameChange(val) {
      const game = this.allGameList.find(item => item.id === val);
      if (game) {
        this.form.gameId = game.id;
        this.form.gameName = game.name;
      }
    },
    handleSubmit() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
        
          const handleApiResult = () => {
            this.$modal.msgSuccess(this.id ? '卡密修改成功' : '卡密创建成功');
            this.$emit('success');
            this.handleClose();
          };

        
          const handleApiError = (error, operation) => {
            console.error(`${operation}卡密失败:`, error);
            // this.$modal.msgError(`${operation}卡密失败: ${error.message || '未知错误'}`);
          };

          try {
            const apiMethod = this.id ? cardSecretApi.editCardSecret : cardSecretApi.createCardSecret;
            if(this.id) {
              this.form.id = this.id
            }
            apiMethod(this.form)
              .then(handleApiResult)
              .catch(error => {
                handleApiError(error, this.id ? '修改' : '创建');
              });
          } catch (error) {
            // 捕获可能的同步错误（如apiMethod不存在）
            console.error('接口调用异常:', error);
            // this.$modal.msgError('操作失败，请重试');
          }

        }
      })
    },
    resetForm() {
      this.id = ''
      this.form = {
        account: '',
        accountId: null,
        username: '',
        expireTime: '',
        remark: '',
        code: ''
      }
      this.$refs.createForm.resetFields()
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
.warning-text {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
    text-align: left;
}
</style>